<template>
  <l-layout :left="240">
    <template #left>
      <l-panel v-if="!isDepartment" :title="$t('公司信息')" style="padding-right: 0">
        <el-tree :data="companyTree" default-expand-all :expand-on-click-node="false" @node-click="handleCompanyClick">
          <span slot-scope="{ node }">
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding: 0">
      <template #toolLeft>
        <div class="l-panel--item" style="color: #333333;margin-right:35px">限定部门
        </div>
        <div class="l-panel--item">
          <el-input style="width: 200px" :placeholder="$t('请输入查询关键字')" v-model="searchWord" size="mini"
            @clear="hanleSearchInput" @input="hanleSearchInput" @keyup.enter.native="hanleSearch">
            <el-button slot="append" icon="el-icon-search" @click="hanleSearch"></el-button>
          </el-input>
        </div>
      </template>
      <l-table :columns="columns" :dataSource="tableData" :loading="selectLoading" :isTree="true" row-key="f_DepartmentId" :isPage="false"
      pidKey="f_ParentId" :isMultiSelect="multiple" @select="handleSelect" @selectAll="handleSelectAll" ref="selectTable">
      </l-table>
    </l-panel>
  </l-layout>
</template>

<script>
  export default {
    props: {
      multiple: {
        type: Boolean,
        default: true,
      },
      // sidx: {
      //   type: String,
      //   default: "F_CreateDate DESC",
      // },
      isDepartment: {
        type: Boolean,
        default: false,
      },
      department: String,
      isChangeSearch: {
        type: Boolean,
        default: false,
      },
      selectlimitDepartment: {
        type: Array,
        default: () => [],
      },
      deleteLimitDepartment: {
        type: Object,
        default: () => { }
      },
      type: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        companyId: "",
        departmentId: "",
        columns: [
          { label: '名称', prop: 'f_FullName', minWidth: '150' },
          { label: '编码', prop: 'f_EnCode', width: '100' },
          { label: '性质', prop: 'f_Nature', width: '80', align: 'center' },
        ],
        value2: "",

        tableData: [], // 展示的数据
        selectLoading: false,
        // tableShowData: [],
        tableTotal: 0,
        tablePageSize: 20,
        tableCurrentPage: 1,
        searchWord: "",
        showType: 1,
        ids: []
      };
    },
    computed: {
      companyTree() {
        if (this.lr_companyTree) {
          return this.lr_companyTree;
        } else {
          return [];
        }
      },
      departmentsTree() {
        if (this.lr_departments) {
          return this.lr_departmentTree(this.lr_departments[this.companyId]);
        } else {
          return [];
        }
      },
      selectedData: {
        get() {
          return this.selectlimitDepartment;
        },
        set(val) {
          this.$emit("update:selectlimitDepartment", val);
        },
      },
    },
    watch: {
      selectedData: {
        handler(n, oldData) {
          n.map(v => {
            v.selectType = this.type
            v.f_RealName = v.f_FullName
          })
          if (!n.length) {
            this.ids = []
            oldData.map(row => {
              this.$refs.selectTable.toggleRowSelection(row, false);
            })
          }
        },
        deep: true
      },
      deleteLimitDepartment: {
        handler(n) {
          this.selectedData = this.selectedData.filter(t => {
            return t.f_DepartmentId !== n.f_DepartmentId
          })
          this.ids = this.ids.filter(id => {
            return id !== n.f_DepartmentId
          })
          let selectRow = this.selectedData.filter(t=>{
            return t.f_DepartmentId == n.f_DepartmentId
          })
          this.$refs.selectTable.toggleRowSelection(selectRow[0], false);
        },
        deep: true,
      }
    },
    created() {
      this.lr_loadCompanys && this.lr_loadCompanys()
      this.tableLoadData();
    },
    methods: {
      handleSelect(selection, row) {
        if (row) {
          //判断新增或删除
          if (this.ids.indexOf(row.f_DepartmentId) === -1) {
            this.selectedData.push(row)
            this.ids.push(row.f_DepartmentId)
          } else {
            this.selectedData = this.selectedData.filter(v => {
              return v.f_DepartmentId !== row.f_DepartmentId
            })
            this.ids = this.ids.filter(v => {
              return v !== row.f_DepartmentId
            })

          }
        }

      },
      handleSelectAll(selection) {
        if (this.tableData.length > 0) {
          if (this.getIsAllChecked()) {
            this.selectedData = selection.concat(this.selectedData);
            selection.map(v => {
              this.ids.push(v.f_DepartmentId)
            })
          } else {
            this.selectedData = []
            this.ids = []
          }

        }

      },
      getIsAllChecked() {
        return this.$refs.selectTable.$refs.learunTable.store.states.isAllSelected
      },
      turnTablePage({ rows }) {
        this.tablePageSize = rows;
        this.tableLoadData(true);
      },

      hanleSearchInput() {
        if (this.isChangeSearch) {
          this.hanleSearch();
        }
      },
      hanleSearch() {
        this.tableLoadData();
      },
      tableLoadData(isNotFirst) {
        if (!isNotFirst) {
          this.tableCurrentPage = 1;
        }
        this.selectLoading = true;
        let queryData = {
          rows: this.tablePageSize,
          page: this.tableCurrentPage,
          keyword: this.searchWord,
          showType: this.showType
        };

        if (this.loadSelectTable) {
          this.loadSelectTable(queryData)
            .then(res => {
              let data = this.$deepClone(res);
              this.tableData = data.rows;
              data.rows.map(row => {
                if (this.ids.indexOf(row.f_DepartmentId) !== -1) {
                  this.$refs.selectTable.toggleRowSelection(row, false);
                }
              })
              this.tableTotal = this.tableData.length

              this.selectLoading = false;
            })
            .catch(() => {
              this.tableData = [];
              this.selectLoading = false;
              this.disabledRefresh = false;
            });
        } else {
          this.disabledRefresh = false;
          this.selectLoading = false;
        }
      },
      async loadSelectTable(postData) {
        await this.lr_loadDepartments(this.companyId)
            let data = this.lr_departments[this.companyId]
            if(!this.$validatenull(postData.keyword)){
                data = data.filter(item => item.f_FullName.indexOf(postData.keyword) >-1 || item.f_EnCode.indexOf(postData.keyword)>-1)
            }
            return {rows:data} 
      },

      handleCompanyClick(node) {
        this.companyId = node.f_CompanyId
        this.tableLoadData();
      },
    },
  };
</script>